package com.example.androidrecorder;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.SurfaceTexture;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.xindawn.droidusbserver.RecorderService;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class VideoDecoderForTextureViewActivity extends Activity implements MediaControlBrocastFactory.IMediaControlListener,PerfOverlayListener {
	final String TAG = getClass().getSimpleName();
	private TextureView surfaceView;
	private TextView performanceOverlayView;
	private boolean enablePerfOverlay = true;
	public  VideoPlayer mVideoPlayer = null;
	private MediaControlBrocastFactory mMediaControlBorcastFactor;

	public static Handler mHandler;
	private RecorderService mPhoneSourceService = null;

	private float mRat;
	private int videoWidth = 0;
	private int videoHeight = 0;

	private static final int VIDEO_SIZE_CHANGE = 0x0003;

	private ImageView imageView;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

		Window window = getWindow();
		WindowManager.LayoutParams params = window.getAttributes();
		params.systemUiVisibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
		window.setAttributes(params);

		mHandler = new Handler(Looper.getMainLooper()){
			@Override
			public void handleMessage(Message msg) {
				switch(msg.what){
					case VIDEO_SIZE_CHANGE:
						Log.d(TAG, "VIDEO_SIZE_CHANGE");
						//onSizeCommand((String)msg.obj);
						break;
				}
			}

		};

		mMediaControlBorcastFactor = new MediaControlBrocastFactory(this);
		mMediaControlBorcastFactor.register(this);

//		int screenwidth = CommonUtil.getScreenWidth(this);
//		int screenHeight = CommonUtil.getScreenHeight(this);

//		int viewWidth = (int)  (screenwidth * 0.75);  // 4/3 = 0.75
//		int viewHeight = (int) (screenHeight * 0.75);

		setContentView(R.layout.mediacodec_player_view);
//		setContentView(R.layout.mediacodec_player_layout);
//		RelativeLayout mainLayout = (RelativeLayout) findViewById(com.example.androidrecorder.R.id.rootframeview);
//		RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(viewWidth, viewHeight);
//		layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);

		FrameLayout container = findViewById(R.id.container);
		ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(
				ViewGroup.LayoutParams.MATCH_PARENT,
				ViewGroup.LayoutParams.MATCH_PARENT);

		mVideoPlayer = new VideoPlayer(this);
		mVideoPlayer.setListener(this);

		surfaceView = new TextureView(this);
		surfaceView.setLayoutParams(layoutParams);
		surfaceView.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {
			@Override
			public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
				Log.d(TAG, "onSurfaceTextureAvailable");
				if (mVideoPlayer != null) {
					Log.d(TAG, "mVideoPlayer start");
					mVideoPlayer.setSurfaceView(new Surface(surface),surfaceView.getWidth(),surfaceView.getHeight());
					mVideoPlayer.start();
				}
			}

			@Override
			public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
			}

			@Override
			public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
				return false;
			}

			@Override
			public void onSurfaceTextureUpdated(SurfaceTexture surface) {
			}
		});

		surfaceView.setOnTouchListener(new View.OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if(mPhoneSourceService != null) {
					mPhoneSourceService.sendHidTouch(event, videoWidth, videoHeight);
					performanceOverlayView.append("\n#####" + event.getAction());
				}
				return true;
			}
		});
		container.addView(surfaceView);

		performanceOverlayView = findViewById(R.id.ios_performanceOverlay);
		performanceOverlayView.bringToFront();

		imageView = findViewById(R.id.item_advert);


		Intent intent = new Intent(this, RecorderService.class);
		intent.setPackage(getPackageName());
		bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
	}

	@Override
	protected void onStart() {
		super.onStart();
		EventBus.getDefault().register(this);
	}

	@Override
	protected void onStop() {
		super.onStop();
		EventBus.getDefault().unregister(this);
	}
	@Override
	protected void onDestroy() {
		unbindService(mServiceConnection);
		mPhoneSourceService = null;
		mMediaControlBorcastFactor.unregister();
		super.onDestroy();
	}

	@Override
	public void finish() {
		// TODO Auto-generated method stub
		super.finish();
	}

	@Override
	public void onStartCommand(int type) {
	}

	@Override
	public void onStopCommand(int type) {
		if(mVideoPlayer != null)
			mVideoPlayer.destory();
		finish();
	}


	@Override
	public void onSize(int width,int height)
	{
		Log.d(TAG,"onSize " + width + "  " + height);
		mHandler.obtainMessage(VIDEO_SIZE_CHANGE, width + "X" + height ).sendToTarget();
	}

	public void onPerfUpdate(final String text) {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				//RecorderService.mLogger.log( "onPerfUpdate: " + text);
				if(enablePerfOverlay) {
					performanceOverlayView.setText(text);
				}
				else {
					performanceOverlayView.setText("");
				}
			}
		});
	}

	public void onSizeCommand(String data)
	{
		String[] videosize = data.split("X");

		int width   = Integer.parseInt(videosize[0]);
		int height  = Integer.parseInt(videosize[1]);

		Log.d(TAG,"VideoPlayer onVideoSizeChanged width=" + width + " height=" + height);
		mRat = ((float) width) / height;
		int screenwidth = (int) (CommonUtil.getScreenWidth(this) * 0.75);
		int screenHeight = (int)(CommonUtil.getScreenHeight(this) * 0.75);
		Log.d(TAG,"VideoPlayer onVideoSizeChanged screenwidth=" + screenwidth + " screenHeight=" + screenHeight);
		if(width > height) {
			if(mRat > 1.77778f) { //iphone x
				if(screenwidth > screenHeight) { //电视横屏
					videoWidth = screenwidth;
					videoHeight = (int) (videoWidth / mRat);
				} else { //电视竖屏
					videoHeight = screenHeight;
					videoWidth = (int) (videoHeight * mRat);
				}
			} else { //iphone, ipad
				if(screenwidth > screenHeight) { //电视横屏
					videoHeight = screenHeight;
					videoWidth = (int) (screenHeight * mRat);
				} else { //电视竖屏
					videoWidth = screenwidth;
					videoHeight = (int) (videoWidth / mRat);
				}
			}
		} else {
			if(screenwidth > screenHeight) { //电视横屏
				videoHeight = screenHeight;
				videoWidth = (int) (videoHeight * mRat);
			} else { //电视竖屏
				videoWidth = screenwidth;
				videoHeight = (int) (videoWidth / mRat);
			}
		}

		Log.d(TAG,"mRat = " + mRat + " videoWidth = " + videoWidth + " videoHeight = " + videoHeight);


		surfaceView.setLayoutParams(new RelativeLayout.LayoutParams(videoWidth, videoHeight));

	}

	private ServiceConnection mServiceConnection = new ServiceConnection() {
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			mPhoneSourceService = ((RecorderService.LocalBinder) service).getService();
			VideoDecoderForTextureViewActivity.this.onServiceConnected();
			Log.d(TAG, "local PhoneSourceActivity onServiceConnected");
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			Log.d(TAG, "local PhoneSourceActivity onServiceDisconnected");
			VideoDecoderForTextureViewActivity.this.onServiceDisconnecting();

		}
	};


	public void onServiceConnected() {

	}

	public void onServiceDisconnecting() {

	}


	@Subscribe(threadMode = ThreadMode.MAIN)
	public void onImageEvent(ImageEvent event) {
		if (event.imageData != null) {
			Bitmap bitmap = BitmapFactory.decodeByteArray(event.imageData, 0, event.imageData.length);
			imageView.setImageBitmap(bitmap); // 更新 UI
		}
	}

}
